<?php
/**
 * Created by ptmall
 * User :  河南邦耀科技有限公司
 * Date : 2020/8/29
 * Time : 13:51
 */

namespace app\api\controller;

use app\admin\model\activity\Tuangou;
use app\common\controller\Api;
use app\common\model\Category;
use fast\Tree;
use mysql_xdevapi\Table;
use think\Db;

class Goods extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    protected $discount;

    public function _initialize()
    {
        parent::_initialize();
        $this->discount = \think\config::get("site.pinggoodspercent") * 0.01;
    }


    /**
     * @Explain :获取商品列表
     * @Date : 2020/8/29 14:49
     * @Author : 河南邦耀网络科技有限公司
     */
    public function search()
    {
        $pn = $this->request->request('pn', 1);
        $keyword = $this->request->request('keyword', '');
        $indexCateId = $this->request->request('indexCateId', 0);
        $recommendId = $this->request->request('recommendId', 0);
        $selfCateId = $this->request->request('selfCateId', 0);
        $orderFiled = $this->request->request('orderField', 0);
        $order = $this->request->request($orderFiled, 'desc');

        $goodsModel = new \app\admin\model\goods\Goods();
        $condition = [];
        if (!empty($keyword)) {
            $cate = Category::get(['name' => $keyword, 'cate_level' => 1]);
            if (!empty($cate)) {
                $cateIds = (new Category())->where(['pid' => $cate['id']])->column('id');
                $cateIds = (new Category())->where(['pid' => ['in', $cateIds]])->column('id');
                $condition['selfCateId'] = ['in', $cateIds];
            } else {
                $condition['title'] = ['like', "%{$keyword}%"];
            }
        }
        if (!empty($indexCateId)) {
            $condition['selfCateId'] = $this->getIndexCateCondition($indexCateId);
        }
        if (!empty($recommendId)) {
            $condition['recommendId'] = $recommendId;
        }
        if (!empty($selfCateId)) {
            $condition['selfCateId'] = $selfCateId;
        }
        $condition['status'] = 1;
        $condition['actid'] = 0;
        $goodsModel->field(['goodsid', 'title', 'image', 'sales', 'price', 'selfCateId', 'discount'])->where($condition)->page($pn, 10);
        $goodsModel->order($this->parseOrder($orderFiled, $order));
        $data = $goodsModel->select();
        $result = [];
        foreach ($data as &$row) {
            $row['spellPrice'] = bcmul($row['price'], $row['discount'] * 0.01, 2);
            if (!in_array($row['goodsid'], [1111, 11111, 111111, 1111111])) {
                $result[] = $row;
            }
        }
        $this->success('ok', $result);
    }

    /**
     * @Explain : 获取商品详情
     * @Date : 2020/8/29 14:44
     * @Author : 河南邦耀网络科技有限公司
     */
    public function detail()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");

        $goodsid = $this->request->request('goodsid', 1);
        $goodsModel = new \app\admin\model\goods\Goods();
        $goodsInfo = $goodsModel->where(['goodsid' => $goodsid, 'status' => 1])->find();
        $skuInfo = Db::table('pt_goods_sku')->where(['itemId' => $goodsid])->find();
        if (empty($goodsInfo) || empty($skuInfo)) {
            $this->error('商品不存在或已下架');
        }
        $goodsInfo = $goodsInfo->toArray();
        $goodsInfo['content'] = json_decode($goodsInfo['content'], true);
        $skuInfo['sku'] = json_decode($skuInfo['sku'], true);
        $skuInfo['props'] = json_decode($skuInfo['props'], true);
        $skuInfo['images'] = json_decode($skuInfo['images'], true);
        $skuInfo['videos'] = json_decode($skuInfo['videos'], true);
        $skuInfo['groupProps'] = json_decode($skuInfo['groupProps'], true);
        $goodsInfo['isCollect'] = 0;
        $goodsInfo['percent'] = $goodsInfo['discount'];
        $goodsInfo['shareUrl'] = \think\config::get('site.aliyunsharedomain');
        $goodsInfo['buyNum'] = 5;
        if($goodsInfo['actid']>0){
            $goodsInfo['isStart'] = Tuangou::where('id',$goodsInfo['actid'])->value('status');
        }
        $goodsInfo['commentCount'] = Db::table('pt_tmall_comment')->where(['itemId' => $goodsid])->count() * 20;
        if ($this->auth->id) {
            $collect = (new \app\admin\model\Collect)->field('id')->where(['uid' => $this->auth->id, 'goodsId' => $goodsid])->find();
            $goodsInfo['isCollect'] = empty($collect) ? 0 : 1;
        }
        $data = array_merge($goodsInfo, $skuInfo);
        $this->success('获取成功', $data);
    }

    /**
     * @Explain : 获取手机号充值商品
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @Date : 2020/10/6 18:53
     * @Author : By Jensen
     */
    public function mobileRecharge()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");

        $cid = $this->request->request('cid', 28);
        $goodsModel = new \app\admin\model\goods\Goods();
        $goods = $goodsModel->where(['indexCategory' => $cid])->select();
        $arr = [
            100 => 70,
            200 => 140,
            500 => 350,
            1000 => 700,
        ];
        foreach ($goods as &$row) {
            $row['spellPrice'] = $arr[(int)$row['price']];
        }
        $this->success('获取成功', $goods);
    }

    public function mobileRecharge2()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $cid = $this->request->request('cid', 28);
        $goodsModel = new \app\admin\model\goods\Goods();
        $goods = $goodsModel->field('goodsid,title,price,sales,commentCount,indexCategory,image,discount')->where(['indexCategory' => $cid, 'status' => 1])->order('goodsid', 'asc')->select();
        foreach ($goods as &$row) {
            $row['spellPrice'] = bcmul($row['price'], $row['discount'] * 0.01, 2);
        }
        $this->success('获取成功', $goods);
    }

    /**
     * @Explain :获取商品分类
     * @Date : 2020/8/31 14:51
     * @Author : 河南邦耀网络科技有限公司
     */
    public function getCategory()
    {
        $data = Category::getCategoryArray('goods_cate');
        $tree = Tree::instance();
        $tree->init($data, 'pid');
        $result = $tree->getTreeArray(0);
        if (empty($result)) {
            $this->success('暂无数据');
        } else {
            $this->success('获取成功', $result);
        }
    }

    /**
     * @Explain :为你推荐
     * @Date : 2020/9/3 15:32
     * @Author : 河南邦耀网络科技有限公司
     */
    public function recommendList()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");

        $category = $this->request->request('category');
        $goodsModel = new \app\admin\model\goods\Goods();
        $condition = ['category' => $category, 'status' => 1];
        $result = $goodsModel->field(['goodsid', 'title', 'image', 'sales', 'price', 'discount'])->where($condition)->limit(6)->order('mtime desc')->select();
        if (empty($result)) {
            $this->success('暂无数据');
        } else {
            foreach ($result as &$row) {
                $row['spellPrice'] = bcmul($row['price'], $row['discount'] * 0.01, 2);
            }
            $this->success('获取成功', $result);
        }
    }

    /**
     * @Explain : 猜你喜欢
     * @Date : 2020/9/11 15:00
     * @Author : 河南邦耀网络科技有限公司
     */
    public function getLike()
    {
        $data = $this->redis->sRandMember('like_goods', 6);
        if (empty($data)) {
            $data = (new \app\admin\model\goods\Goods())->field(['goodsid', 'title', 'image', 'sales', 'price', 'discount'])
                ->where(['status' => 1])->order('commentCount desc')->limit(200)->select();
            foreach ($data as $row) {
                $this->redis->sAdd('like_goods', json_encode($row, JSON_UNESCAPED_UNICODE));
            }
            $this->redis->expire('like_goods', 86400);
            $data = $this->redis->sRandMember('like_goods', 6);
        }
        foreach ($data as &$row) {
            $row = json_decode($row, true);
            $row['spellPrice'] = bcmul($row['price'], $row['discount'] * 0.01, 2);
        }
        if ($data) {
            $this->success('ok', $data);
        } else {
            $this->error('暂无商品信息');
        }
    }

    /**
     * @Explain :浏览记录
     * @Date : 2020/9/16 17:10
     * @Author : 河南邦耀网络科技有限公司
     */
    public function getInfo()
    {
        $goodsIds = $this->request->request('goodsId', '');
        if (empty($goodsIds)) $this->success('暂无浏览商品数据');
        $goodsModel = new \app\admin\model\goods\Goods();
        $goodsList = explode(",", $goodsIds);
        foreach ($goodsList as $ks => $vs) {
            $row = $goodsModel->field(['goodsid', 'title', 'image', 'sales', 'price', 'selfCateId', 'discount'])->where('goodsid', $vs)->find();
            $row['spellPrice'] = bcmul($row['price'], $row['discount'] * 0.01, 2);
            $data[] = $row;
        }
        $this->success('ok', $data);
    }

    private function parseOrder($field, $order)
    {
        if ($field == 'price') {
            return ['price ' => $order];
        } elseif ($field == 'sales') {
            return ['sellCount' => $order];
        }
        return [];
    }

    private function getIndexCateCondition($id)
    {
        $cateName = Db::table('pt_self_cate')->where(['id' => $id])->value('title');
        $cate = Category::get(['name' => $cateName, 'cate_level' => 1]);
        $cateIds = (new Category())->where(['pid' => $cate['id']])->column('id');
        $cateIds = (new Category())->where(['pid' => ['in', $cateIds]])->column('id');
        return !empty($cateIds) ? ['in', $cateIds] : [];
    }

}
